package com.itheima.service;

import com.itheima.client.NoticeClient;
import com.itheima.dao.ArticleDao;
import com.itheima.pojo.Article;
import com.itheima.pojo.Notice;
import com.itheima.utile.IdWorker;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;
import java.util.Set;

@Service
public class ArticleService {
    @Autowired
    ArticleDao articleDao;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    NoticeClient noticeClient;
    @Autowired
    RabbitTemplate rabbitTemplate;
    public Article get(String id) {

        return articleDao.selectById(id);
    }

    public void add(Article article,IdWorker idWorker) {
        article.setVisits(0);   //浏览量
        article.setThumbup(0);  //点赞数
        article.setComment(0);  //评论数
        articleDao.insert(article);
        //将文章的添加消息推送给其他订阅该文章的用户
        String userid = article.getUserid();//获取到作者id
        String articleKey="authorIdKey:"+userid;
        //根作者id的key查询订阅了该作者的用户
        Set<String> members = redisTemplate.boundSetOps(articleKey).members();
        for (String members1 : members){
           //获取到每个用户的id，将其存储到消息的数据库中
            Notice notice = new Notice();
            notice.setId(String.valueOf(idWorker.nextId()));
            notice.setOperatorId(userid); //发送的id
            notice.setReceiverId(members1);//接受的id
            notice.setTargetId(article.getId());//文章id
            notice.setCreatetime(new Date());//新建的时间
            notice.setTargetType("article");
            notice.setAction("publish");
            notice.setType("sys");
            notice.setState("0");
            noticeClient.add(notice);
        }

        // 当新增文章时，就通过消息队列发送 路由键是作者id
        rabbitTemplate.convertAndSend("tensquare_exchange",userid,"你关注的作者id为"+userid+"已发布新文章");


    }

    public Boolean subscribe(Map map) {
        String userId = (String) map.get("userId");//用户id
        String articleId = (String) map.get("articleId");//文章id
        String authorId = articleDao.selectById(articleId).getUserid();//作者id
        String userKey="userKey:"+userId;
        String authorKey="authorIdKey:"+authorId;
        //判断用户是否已经订阅了作者
        Boolean member = redisTemplate.boundSetOps(userKey).isMember(articleId);
        //声明消息队列管理器
        RabbitAdmin rabbitAdmin = new RabbitAdmin(rabbitTemplate.getConnectionFactory());
        //声明交换机
        DirectExchange tensquare_exchange = new DirectExchange("tensquare_exchange");
        rabbitAdmin.declareExchange(tensquare_exchange);
        //为每一个用户创建一个队列
        Queue queue = new Queue("tensquare_queue_"+userId,true);//这里使用的是订阅用户的id，不是作者id
        //绑定交换机和队列
        Binding with = BindingBuilder.bind(queue).to(tensquare_exchange).with(authorId);

        if(member){
            //代表用户的set集合中已经包含了该作者，那就执行取消订阅
            redisTemplate.boundSetOps(userKey).remove(articleId);
            redisTemplate.boundSetOps(authorKey).remove(userId);
            //取消订阅，解绑交换机和队列的关系
            rabbitAdmin.removeBinding(with);
            return false;
        }else{
            //代表用户的set集合中没有包含了该作者
            redisTemplate.boundSetOps(userKey).add(authorId);
            redisTemplate.boundSetOps(authorKey).add(userId);
            //订阅成功，绑定交换机和队列的关系
            rabbitAdmin.declareQueue(queue);
            rabbitAdmin.declareBinding(with);
            return true;
        }

    }

    public Boolean thumbup(Map<String,String> map) {
        String userId = map.get("userId");
        String articleId = map.get("articleId");
        String key ="thumbup_article_"+articleId+"_userId_"+userId;
        Object o = redisTemplate.boundValueOps(key).get();
        if(o==null){
            redisTemplate.opsForValue().set(key,"1");
            Article article = articleDao.selectById(articleId);
            article.setThumbup(article.getThumbup()+1);
            articleDao.updateById(article);
            //发送点赞通知消息
            Notice notice = new Notice();
            notice.setReceiverId(article.getUserid());
            notice.setOperatorId(userId);
            notice.setAction("thumbup");
            notice.setTargetType("article");
            notice.setTargetId(articleId);
            notice.setCreatetime(new Date());
            notice.setType("user");
            notice.setState("0");
            noticeClient.add(notice);
            //将点赞消息存储到队列中
            RabbitAdmin rabbitAdmin = new RabbitAdmin(rabbitTemplate.getConnectionFactory());
            Queue queue = new Queue("thumbup_queue_"+article.getUserid(),true);
            rabbitAdmin.declareQueue(queue);
            rabbitTemplate.convertAndSend("thumbup_queue_"+article.getUserid(),"用户"+userId+"点赞了你的文章");
            return true;
        }else{
           return false;
        }

    }
}
